package com.dkd.rollback;

import cn.elegent.actx.annotation.RollBack;
import cn.elegent.actx.context.Snapshot;
import cn.elegent.actx.core.rollback.RollBackHandler;
import cn.elegent.pay.ElegentPay;
import cn.elegent.pay.dto.RefundRequest;
import com.dkd.config.ACTXConfig;
import com.dkd.config.constant.OrderStatus;
import com.dkd.config.constant.PayStatus;
import com.dkd.contract.VendoutContract;
import com.dkd.entity.OrderEntity;
import com.dkd.service.OrderService;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author DiXiaoNie
 * @since 2023/2/5 16:32
 */
@RollBack(mainName = ACTXConfig.ORDER_VENDOUT_PAY, childName = ACTXConfig.ORDER_VENDOUT_PAY)
@Slf4j

public class PayErrorRollBack implements RollBackHandler {

    @Autowired
    private ElegentPay elegentPay;

    @Autowired
    private OrderService orderService;

    /**
     * 做回滚
     *
     * @param topic    主题
     * @param snapshot 快照
     * @author DiXiaoNie
     * @date 2023/02/05
     */
    @Override
    public void doRollBack(String topic, Snapshot snapshot) throws Exception {
        log.info("收到了回滚的消息来自：" + topic + ",数据 " + snapshot.getData());
        VendoutContract vendoutContract = snapshot.findData("vendoutContract", VendoutContract.class);
        //如果取不到快照就return 不做处理
        if (vendoutContract == null) {
            return;
        }
        //修改订单状态
        if (Strings.isNullOrEmpty(vendoutContract.getInnerCode())) {
            return;
        }
        String orderNo = vendoutContract.getVendoutData().getOrderNo();
        OrderEntity orderEntity = this.orderService.getByOrderNo(orderNo);
        //处理出货逻辑
        orderEntity.setStatus(OrderStatus.ORDER_STATUS_VENDOUT_FAIL);
        orderEntity.setPayStatus(PayStatus.PAY_STATUS_REFUNDING);
        log.info("出货失败，发起退款 订单号：{}", orderNo);
        this.orderService.updateById(orderEntity);
        //发起退款
        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setTotalFee(vendoutContract.getVendoutData().getAmount());
        refundRequest.setRefundAmount(vendoutContract.getVendoutData().getAmount());
        refundRequest.setOrderSn(vendoutContract.getVendoutData().getOrderNo());
        this.elegentPay.refund(refundRequest, orderEntity.getPayType());
    }
}
